<?php

namespace App\Modules\Popularize\Platform;

use App\Http\Model\AdvertiserCallbackLog;
use App\Http\Model\Device;
use App\Http\Model\Hint;
use App\Http\Model\MonitoringLink\AccessToken;
use App\Http\Model\MonitoringLink\HuaweiCallbackLogs;
use App\Http\Model\UserRegisterLog;
use App\Http\Services\AdvertiserCallbackLogServices;
use App\Http\Services\DeviceServices;

class PlatformToutiao implements PlatformInterface
{

    protected $callback;
    protected $platform;
    protected $device;
    protected $userId;

    const ACTIVITE_EVENT = 0;
    const REGISTER_EVENT = 1;
    const PAY_EVENT = 2;

    public function __construct($callback, $platform, $device, $userId)
    {
        $this->callback = $callback;
        $this->platform = $platform;
        $this->device = $device;
        $this->userId = $userId;
    }

    public function active(): ?bool
    {

        //查询是否存在设备信息，如果存在就说明设备已经激活
        $deviceModel = new Device();
        $deviceInfo = $deviceModel->getByGuid($this->device->guid);
        $device = $deviceInfo[0] ?? [];
        if (!empty($device)) {
            return true;
        }

        //处理激活
        $params = json_decode(json_encode($this->device), true);
        $params = $this->_checkField($params);

        if (empty($this->device->guid)) {
            write_log('Platform', 'platform_toutiao', ["激活时guid为空", $params]);
            return false;
        }
        try {
            $deviceModel = new Device();
            $deviceModel->save($params);

            $this->_report(self::ACTIVITE_EVENT);

            write_log('Platform', 'platform_toutiao', ["保存设备信息成功", $params]);

            return true;
        } catch (\Exception $e) {
            write_log('Platform', 'platform_toutiao', ["保存设备信息失败", $params, $e->getMessage()]);
            return false;
        }
    }

    public function regist(): ?bool
    {
        return $this->_report(self::REGISTER_EVENT);
    }

    public function pay($amount = 0): ?bool
    {
        //校验注册天数
        $date = strtotime('+8 day', strtotime(date('Y-m-d', $this->device->created_at)));
        if (time() > $date) {
            return false;
        }
        return $this->_report(self::PAY_EVENT, $amount * 100);
    }

    private function _report($type, $amount = 0)
    {
        try {
            $url = $this->callback . '&event_type=' . $type . '&conv_time=' . time();
            if ($type == self::PAY_EVENT && $amount > 0) {
                $url .= '&pay_amount=' . $amount;
            }

            $result = curlRequest($url, null, false, [], 3);
            write_log('toutiaoAdvertiser', 'toutiao report', ['url' => $url, 'type' => $type, 'amount' => $amount]);
        } catch (\Exception $exception) {
            write_log('toutiaoAdvertiser', 'toutiao report', ['url' => $url, 'type' => $type, 'amount' => $amount, 'error_msg' => $exception->getMessage()]);
            return false;
        }
        $result = json_decode($result);

        return isset($result->code) && $result->code == 0;
    }

    protected function _checkField($params = [])
    {
        do {
            $checkField = ['cid', 'aid', 'callback', 'advertiser_id', 'guid', 'idfa', 'version_no', 'os_name', 'device', 'channel_id', 'platform', 'imei', 'oaid', 'adid', 'conv_ext', 'client_ip'];
            if (empty($params)) {
                break;
            }

            $inputParams = [];
            foreach ($checkField as $field) {
                if (array_key_exists($field, $params)) {
                    $inputParams[$field] = $params[$field];
                }
            }

            $params = $inputParams;
        } while (false);

        return $params;
    }
}
